package com.example.chatgptapplication.service.impl;


import com.example.chatgptapplication.entity.deepseek.DeepSeekRequest;
import com.example.chatgptapplication.entity.deepseek.DeepSeekResponse;
import com.example.chatgptapplication.service.DeepSeekService;
import com.example.chatgptapplication.websocket.WebSocketChannel;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class DeepSeekServiceImpl implements DeepSeekService {

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    private final RestTemplate restTemplate = new RestTemplate();


    public String callDeepSeek(String userMessage, List<DeepSeekRequest.Message> deep) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", "Bearer " + apiKey);

        // 构建请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");
        deep.add(new DeepSeekRequest.Message("user",userMessage));
        request.setMessages(deep);
//        request.setStream(true);

        // 发送请求
        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);
        ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                apiUrl, HttpMethod.POST, entity, DeepSeekResponse.class);

        // 解析响应
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
//            WebSocketChannel.chatHistoryHashMap.
            deep.add(new DeepSeekRequest.Message("assistant",response.getBody().getChoices().get(0).getMessage().getContent()));
            return response.getBody().getChoices().get(0).getMessage().getContent();
        } else {
            throw new RuntimeException("Failed to call DeepSeek API: " + response.getStatusCode());
        }
    }



    public Flux<String> streamDeepSeekResponse(String userMessage, String apiKey) {
        // 1. 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        // 2. 构建流式请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");
        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        messages.add(new DeepSeekRequest.Message("user", userMessage));
        request.setMessages(messages);
        request.setStream(true); // 关键：开启流式模式

        // 3. 创建WebClient实例
        WebClient webClient = WebClient.create(apiUrl);

        // 4. 发送流式请求
        return webClient.post()
                .uri(apiUrl)
                .headers(httpHeaders -> httpHeaders.addAll(headers))
                .bodyValue(request)
                .accept(MediaType.TEXT_EVENT_STREAM) // 接受SSE流
                .retrieve()
                .bodyToFlux(String.class)
                .map(this::parseStreamResponse)
                .onErrorResume(e -> {
                    // 错误处理逻辑
                    return Flux.error(new RuntimeException("Stream error: " + e.getMessage()));
                });
    }

    // 流式响应解析方法
    private String parseStreamResponse(String chunk) {
        try {
            // 假设响应格式为SSE（data: {...}）
            if (chunk.startsWith("data: ")) {
                String json = chunk.substring(6).trim();
                ObjectMapper mapper = new ObjectMapper();
                JsonNode node = mapper.readTree(json);

                // 提取内容
                if (node.has("choices")) {
                    JsonNode choices = node.get("choices");
                    if (choices.isArray() && choices.size() > 0) {
                        return choices.get(0)
                                .path("delta")
                                .path("content")
                                .asText("");
                    }
                }
            }
            return "";
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse stream chunk", e);
        }
    }
}
